import { Suspense, useEffect, useRef } from "react";
import { Canvas, useThree } from "@react-three/fiber";
import {
  useGLTF,
  OrbitControls,
  Environment,
  Lightformer,
  Bounds,
  useProgress,
  Html,
} from "@react-three/drei";
import * as THREE from "three";

// 调试光源组件 (修复了条件调用 Hook 的问题)
function DebugLights() {
  const dirLightRef = useRef();
  const pointLightRef = useRef();

  // 在开发环境下显示辅助线
  useEffect(() => {
    if (process.env.NODE_ENV === "development") {
      const directionalLightHelper = new THREE.DirectionalLightHelper(
        dirLightRef.current,
        1,
        "red"
      );
      const pointLightHelper = new THREE.PointLightHelper(
        pointLightRef.current,
        1,
        "blue"
      );

      return () => {
        directionalLightHelper.dispose();
        pointLightHelper.dispose();
      };
    }
  }, []);

  return (
    <>
      <ambientLight intensity={0.1} />
      <directionalLight
        ref={dirLightRef}
        position={[5, 10, 7]}
        intensity={1.5}
        castShadow
        shadow-mapSize={[2048, 2048]}
        shadow-camera-far={50}
      />
      <pointLight
        ref={pointLightRef}
        position={[-5, 5, -5]}
        intensity={20}
        color="#ff0055"
      />
    </>
  );
}

// 其余组件保持不变...
function Loader() {
  const { progress } = useProgress();
  return (
    <Html center>
      <div style={{ color: "white" }}>{Math.round(progress)}% loaded</div>
    </Html>
  );
}

function Model({ url, scale = 1 }) {
  const { scene, materials } = useGLTF(url);
  const groupRef = useRef();

  useEffect(() => {
    // ...原有模型处理逻辑
  }, [scene, materials]);

  return (
    <group ref={groupRef} scale={scale}>
      <primitive object={scene} />
    </group>
  );
}

// 主场景组件
export default function SplineViewer() {
  const modelUrl = "/dgp.glb";

  return (
    <div style={{ width: "100vw", height: "100vh" }}>
      <Canvas
        shadows
        camera={{ position: [0, 0, 5], fov: 50 }}
        gl={{ preserveDrawingBuffer: true }} // 允许截图
      >
        <color attach="background" args={["#101010"]} />

        <Suspense fallback={<Loader />}>
          <DebugLights />

          {/* 环境反射 */}
          <Environment files="/studio_small_03_1k.hdr" intensity={0.3}>
            <Lightformer
              intensity={2}
              rotation-x={Math.PI / 2}
              position={[0, 5, -9]}
              scale={[10, 10, 1]}
            />
          </Environment>

          {/* 模型容器 */}
          <Bounds fit clip observe margin={1.2}>
            <Model url={modelUrl} scale={0.8} />
          </Bounds>

          {/* 辅助网格 */}
          <gridHelper args={[10, 10]} position={[0, -1, 0]} />
        </Suspense>

        <OrbitControls
          makeDefault
          enablePan={true}
          enableZoom={true}
          enableRotate={true}
        />
      </Canvas>
    </div>
  );
}
